<template>
  <div>
     <!-- 头部 -->
    <home-head></home-head>
    <!--/ 头部 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <div class="wrap">
       <!-- 轮播 -->
       <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item
          v-for="banner in banners"
          :key="banner.id"
        >
          <img :src="banner.picUrl" alt="">
        </van-swipe-item>
      </van-swipe>
       <!-- /轮播 -->
       <!-- 宫格导航 -->
       <van-grid>
        <van-grid-item
          v-for="cate in cates"
          :key="cate.id"
          :icon="cate.icon"
          :text="cate.name"
          @click="enterItemList(cate.id)"
          />
      </van-grid>
       <!-- /宫格导航 -->
       <!-- 精品推荐 -->
      <recommend
        :recommends = "recommends"
        @click="clickItem"
        @clickAddCart="add_cart"
      />
       <!-- /精品推荐 -->
    </div>
    </van-pull-refresh>
    <!-- tabbar -->
     <my-tabbar></my-tabbar>
     <!-- /tabbar -->
  </div>
</template>

<script>
import MyTabbar from '@components/MyTabbar'
import HomeHead from './components/HomeHead'
import Recommend from './components/Recommend'
import { getCates, getHomeBanners, getRecommends } from '@api'
import { mapActions } from 'vuex'
import { Toast } from 'vant'
export default {
  data () {
    return {
      banners: [],
      cates: [],
      recommends: [],
      isLoading: false
    }
  },
  created () {
    this.fetchBanners()
    this.fetchCates()
    this.fetchRecommends()
  },
  methods: {
    add_cart (item) {
      // 点击加入购物车按钮
      console.log(item)
      // 处理默认选中以及默认num为1问题
      item.isChecked = true
      item.num = 1
      this.addCart(item)
      Toast('成功加入购物车')
    },
    enterItemList (cateId) {
      // 进入 商品列表
      this.$router.push(`/itemLists/${cateId}`)
    },
    clickItem (id) {
      // 点击进入详情页
      this.$router.push({
        path: '/detail',
        query: {
          id
        }
      })
    },
    onRefresh () {
      // 数据更新
      this.fetchRecommends()
    },
    fetchBanners () {
      // banner数据获取
      getHomeBanners().then(res => {
        if (res.data.code === 0) {
          this.banners = res.data.data
        }
      })
    },
    fetchCates () {
      // 分类获取
      getCates().then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          this.cates = res.data.data
        }
      })
    },
    fetchRecommends () {
      // 推荐商品获取
      getRecommends().then(res => {
        console.log(res)
        this.isLoading = false
        if (res.data.code === 0) {
          this.recommends = res.data.data
        }
      })
    },
    ...mapActions('cart', ['addCart'])
  },
  components: {
    MyTabbar,
    HomeHead,
    Recommend
  }
}
</script>

<style lang="scss" scoped>
.my-swipe{
  img{
    width:100%;
  }
}
/*
/deep/ .van-grid-item{
  .van-grid-item__text{
    font-size:20px;
  }
}*/
</style>
